<?php
/**
 * Created by PhpStorm.
 * User: jim
 * Date: 2016-12-26
 * Time: 8:49
 */

namespace App\Models;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

class Sender extends Model
{
    protected $table = 'sender';

    protected $guarded = ['id'];

    public function checkLogin(Request $request)
    {
        $username = $request->input('username');
        $password = $request->input('password');
        $password = md5($password);
        $ob = $this->where([['username', '=', $username], ['password', '=', $password]])->first();
        if ($ob) {
            return $ob;
        } else {
            return null;
        }

    }

    public function store()
    {
        return $this->belongsTo('App\Models\Store','store_id','id');
    }

    //查询商家下的快递员
    public function selSender()
    {
        $id = 1;
        $bo = $this->where('store_id',$id)->get();
        if($bo->count() >0){
            return $bo;
        }else{
            return null;
        }
    }

    public function upinfo(Request $request, $id)
    {
        if ($request->hasFile('xphoto')) {
            if ($request->file('xphoto')->isValid()) {
                $file = $request->file('xphoto');
                $ext = $file->getClientOriginalExtension();
                $picname = time() . rand(1000, 9999) . '.' . $ext;
                $file->move('upload/sender', $picname);
                if ($file->getError() > 0) {
                    return null;
                }
            }
        }

        $data = $request->only('name','phone', 'store_id', 'photo');
        if (isset($picname)) {
            if ($data['photo'] != 'sen_default.jpg') {
                unlink("upload/sender/{$data['photo']}");
            }
            Image::make('upload/sender/'.$picname)->resize('200','200')->save('upload/sender/'.$picname);
            $data['photo'] = $picname;
        }
        $row = $this->where('id', $id)->update($data);
        if ($row) {
            return $row;
        } else {
            return null;
        }
    }
}